package sk.marek.barak.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

import sk.marek.barak.client.UserInformation;
import sk.marek.barak.shared.Util;

public class LoggedInGAEDAO implements LoggedInDAO {

	@Override
	public void loggedIn() {
		User curent =UserServiceFactory.getUserService().getCurrentUser();
		Key key = KeyFactory.createKey("LoggedIn",curent.getUserId());
		Entity entity =Util.findEntity(key);
		if(entity==null)
		entity = new Entity("LoggedIn",curent.getUserId());
		entity.setProperty("userId",curent.getUserId());
		Util.persistEntity(entity);
	}

	@Override
	public void loggedOut() {
		User curent =UserServiceFactory.getUserService().getCurrentUser();
		Key key = KeyFactory.createKey("LoggedIn",curent.getUserId());
		
		Entity entity = Util.findEntity(key);
		if(entity!=null)
			Util.deleteEntity(key);
	}

	@SuppressWarnings("deprecation")
	@Override
	public List<UserInformation> getLoogedInUsers() {
		Iterable<Entity> loggedInUsers=Util.listEntities("LoggedIn", null, null);
		List<UserInformation> userInformation = new ArrayList<UserInformation>();		
		for(Entity en: loggedInUsers){
			Key key = KeyFactory.createKey("UserInfo", en.getProperty("userId").toString());
			Entity userIfo = Util.findEntity(key);
			UserInformation user = new UserInformation();
			user.setUserID(en.getProperty("userId").toString());
			user.setBirthDate(new Date(userIfo.getProperty("date").toString()));
			user.setName(userIfo.getProperty("nickName").toString());
			userInformation.add(user);
		}
		
		
		return userInformation;
		
	}

}
